package Hot100;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class 腐烂的橘子 {

    int count = 0;

    public int orangesRotting(int[][] grid) {
        int rLen = grid.length;
        int cLen = grid[0].length;
        List<int[]> list = new ArrayList<>();
        for (int i = 0; i < rLen; i++) {
            for (int j = 0; j < cLen; j++) {
                if (grid[i][j] > 0) count++;
                if (grid[i][j] == 2) list.add(new int[]{i, j, 0});
            }
        }
        int res = bfs(grid, list);
        if (count > 0) return -1;
        return res;
    }

    private int bfs(int[][] grid, List<int[]> list) {
        Queue<int[]> queue = new LinkedList<>();
        for (int[] start : list) queue.offer(start);
        int time = 0;
        while (!queue.isEmpty()) {
            int[] coord = queue.poll();
            count--;
            int r = coord[0];
            int c = coord[1];
            int t = coord[2];
            grid[r][c] = t;
            time = -t;
            enqueue(grid, r - 1, c, t - 1, queue);
            enqueue(grid, r + 1, c, t - 1, queue);
            enqueue(grid, r, c - 1, t - 1, queue);
            enqueue(grid, r, c + 1, t - 1, queue);
        }
        return time;
    }

    private void enqueue(int[][] grid, int i, int j, int k, Queue<int[]> queue) {
        if (i >= 0 && i < grid.length && j >= 0 && j < grid[0].length && grid[i][j] == 1) {
            queue.offer(new int[]{i, j, k});
            grid[i][j] = 2;
        }
    }
}
